<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="日期">
          <el-date-picker
            v-model="searchParam.requireDateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="getrequireDate"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择产品"
            clearable
            @keyup.enter="search"
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchParam.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in statusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mesplanmonthplanactual/export',
              '月度生产计划实际表',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
        <!--<el-button
          type="success"
          :disabled="ids.length === 0"
          @click="saveBatchDayPlan"
          >生成日计划</el-button
        >-->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        :max-height="tableHeight"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          label="序号"
          width="70"
          key="id"
          align="center"
        />
        <el-table-column
          label="产品图号"
          prop="figureNumber"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品名称"
          prop="materialName"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="包装规格"
          prop="materialSpecification"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="日期"
          prop="requireDate"
          min-width="100"
          show-overflow-tooltip
          :formatter="formatDate"
          align="center"
        />
        <el-table-column
          label="计划数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="实际数量"
          prop="finishQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="状态"
          prop="status"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1">已生成</el-tag>
            <el-tag v-else>未生成</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人名"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[100, 10, 25, 50]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import {useTable, useDownload, useDictionary, useComputeTableHeight} from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESPLANMONTHPLANACTUAL",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesplanmonthplanactual/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialId: "",
  materialCode: "",
  materialName: "",
  status: "",
  requireDateSearch: [],
  requireDateStart: "",
  requireDateEnd: "",
};

const deleteParam = {
  api: "/mes/mesplanmonthplanactual/delete",
  data: {},
};
const statusList = [
  {
    id: "0",
    name: "未生成",
  },
  {
    id: "1",
    name: "已生成",
  },
];
// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam,
  100
);

const tableHeight = ref<any>("auto");
onMounted(() => {
  getTableList();
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesplanmonthplanactual/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开月度生产计划实际表表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改月度生产计划实际表";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增月度生产计划实际表";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开月度生产计划实际表表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "月度生产计划实际表详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
const isConfirm = (row: { status: number }, index: number) => {
  return row.status === 0;
};
function getrequireDate(data: any) {
  if (data) {
    searchParam.value.requireDateStart = data[0];
    searchParam.value.requireDateEnd = data[1];
  } else {
    searchParam.value.requireDateStart = "";
    searchParam.value.requireDateEnd = "";
  }
}

//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
async function saveBatchDayPlan(id: any) {
  ElMessageBox.confirm("确认对已选中的数据生产日计划吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await request({
      url: `/mes/mesplanmonthplanactual/saveBatchDayPlan`,
      method: "post",
      data: { ids: ids.value },
    });
    if (res.code === 200 && res.data) {
      ElMessage.success("日计划生成成功！");
    }
    search();
  });
}
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};
</script>
